<?php
function connectDB()
{
  $host = "localhost";
  $user = "alexey";
  $pass = "alex_lazer";
  $link_id = mysql_connect($host, $user, $pass);
  mysql_select_db('fly', $link_id) or die(mysql_error());
  mysql_query("SET NAMES 'utf8'");
  mysql_query("SET CHARACTER SET 'utf8'");
  return $link_id;
}

function init()
{
  session_start();
  if ($_SESSION['id'] != '') {
    return true;
  } else if (isset($_COOKIE['login']) && isset($_COOKIE['pass'])) {
    if (loginUser($_COOKIE['login'], $_COOKIE['pass'])) {
      return true;
    }
  } else {
    setLocaleLanguage();
    return false;
  }
}

function setLocaleLanguage(){

}

function setLanguage()
{
  $_SESSION['lang'] = "lang." . getUserLanguage();
}

function getUserLanguage()
{
  $paramArray = null;
  $paramArray['uid'] = $_SESSION['id'];
  $row = mysql_fetch_assoc(\controller\SQLManipulator::execute('select-user-lang', $paramArray));
  return $row['lang'];
}

function setUserLanguage($lang) {
  $paramArray = null;
  $paramArray['uid'] = $_SESSION['id'];
  $paramArray['lang'] = $lang;
  \controller\SQLManipulator::execute('update-user-lang', $paramArray);
}

function display()
{
  if (init()) {
    echo "style='display: block'";
  } else echo "style='display: none'";
}

function getResponseComments($start, $end, $nid)
{
  $paramArray = null;
  $paramArray['new_id'] = $nid;
  $paramArray['start'] = $start - 1;
  $paramArray['end'] = $end;
  return \controller\SQLManipulator::execute('select-response-comments', $paramArray);
}

function getResponseImages($rid)
{
  $paramArray = null;
  $paramArray['response_id'] = $rid;
  return \controller\SQLManipulator::execute('select-response-images', $paramArray);
}

function countPages($newsId)
{
  $paramArray = null;
  $paramArray['new_id'] = $newsId;
  $resultSet = \controller\SQLManipulator::execute('select-count-new-pages', $paramArray);
  $row = mysql_fetch_assoc($resultSet);
  return ceil($row['rec'] / 20);
}

function getResponseComment($id)
{
  $paramArray = null;
  $paramArray['response_id'] = mysql_real_escape_string($id);
  return \controller\SQLManipulator::execute('select-response-comment', $paramArray);
}

function getFormattedTime()
{
  $microtime = microtime();
  $microtime = str_replace(" ", "", $microtime);
  $microtime = str_replace(".", "", $microtime);
  return $microtime;

}

function getAvatarSrc($id)
{
  $paramArray = null;
  $paramArray['user_id'] = mysql_real_escape_string($id);
  $resultSet = \controller\SQLManipulator::execute('select-avatar-path', $paramArray);
  $row = mysql_fetch_assoc($resultSet);
  return $row['image'];
}

function startTransaction()
{
  mysql_query("SET AUTOCOMMIT=0");
  mysql_query("BEGIN");
}

function commitTransaction()
{
  mysql_query("COMMIT");
}

function rollbackTransaction()
{
  mysql_query("ROLLBACK");
}

function getLastComments($topicId)
{
  $paramArray = null;
  $paramArray['topic_id'] = mysql_real_escape_string($topicId);
  return $resultSet = \controller\SQLManipulator::execute('select-last-topic-messages', $paramArray);
}

function getTopics($userId)
{
  $resultArray = null;
  $resultArray['user_id'] = mysql_real_escape_string($userId);
  return \controller\SQLManipulator::execute('select-user-topics', $resultArray);
}

function getTextPart($text, $symbols)
{
  if (strlen($text) > $symbols) {
    if ($text{$symbols} != " ") {
      $n = strpos($text, " ", $symbols);
      return substr($text, 0, $n) . "...";
    } else {
      return substr($text, 0, $symbols) . "...";
    }
  } else return $text . "...";
}

function countTopicMessages($topicId)
{
  $paramArray = null;
  $paramArray['topic_id'] = mysql_real_escape_string($topicId);
  $topicSet = \controller\SQLManipulator::execute('select-count-topic-messages', $paramArray);
  $topic = mysql_fetch_assoc($topicSet);
  if ($topicSet) {
    return $topic['cmsg'];
  } else {
    return 0;
  }
}

function pagesFromMessages($messages)
{
  $pages = ceil($messages / 20);
  return $pages;
}

function getStat($userId)
{

  $paramArray = null;
  $paramArray['user_id'] = mysql_real_escape_string($userId);
  return $userSet = \controller\SQLManipulator::execute('select-user-statistics', $paramArray);
}

function getUserGroups()
{
  $paramArray = null;
  $paramArray['user_id'] = $_SESSION['id'];
  return \controller\SQLManipulator::execute('select-user-groups', $paramArray);
}

function countGroupMembers($groupId)
{
  $paramArray = null;
  $paramArray['group_id'] = mysql_real_escape_string($groupId);
  $userGroupsSet = \controller\SQLManipulator::execute('select-count-group-members', $paramArray);
  if ($userGroupsSet) {
    $users = mysql_fetch_assoc($userGroupsSet);
    return $users['users'];
  } else {
    return 0;
  }
}

function getOtherGroups()
{
  return \controller\SQLManipulator::execute('select-user-other-groups', null);
}

function getUserInfo($id)
{
  $paramArray = null;
  $paramArray['user_id'] = mysql_real_escape_string($id);

  $resultSet = \controller\SQLManipulator::execute('select-user-info', $paramArray);
  if ($resultSet) {
    return mysql_fetch_assoc($resultSet);
  } else {
    return null;
  }

}

function getUserVisibility()
{
  $paramArray = null;
  $paramArray['user_id'] = $_SESSION['id'];
  $visResultSet = \controller\SQLManipulator::execute('select-user-visibility', $paramArray);

  if ($visResultSet) {
    $visRow = mysql_fetch_assoc($visResultSet);
    $vis = $visRow['visible'];
    return $vis;
  } else {
    return 0;
  }

}

function getGalleryVisibility()
{
  $paramArray = null;
  $paramArray['user_id'] = $_SESSION['id'];
  $visResultSet = \controller\SQLManipulator::execute('select-user-gallery-visibility', $paramArray);
  if ($visResultSet) {
    $visRow = mysql_fetch_assoc($visResultSet);
    $vis = $visRow['galvis'];
    return $vis;
  } else {
    return 0;
  }

}

function isWaitingForDelete()
{
  $paramArray = null;
  $paramArray['user_id'] = $_SESSION['id'];
  $resultSet = \controller\SQLManipulator::execute('select-user-is-waiting-for-delete', $paramArray);
  if ($resultSet) {
    $resRow = mysql_fetch_assoc($resultSet);
    return $resRow['del'];
  } else {
    return 0;
  }
}

function getUserGroup($id)
{
  $paramArray = null;
  $paramArray['user_id'] = mysql_real_escape_string($id);
  $resultSet = \controller\SQLManipulator::execute('select-user-group', $paramArray);

  if ($resultSet) {
    $resRow = mysql_fetch_assoc($resultSet);
    return $resRow['rights'];
  } else {
    return 0;
  }
}

function getUsersGallery($id)
{
  $usersGalleryRights = getUserGroup($_SESSION['id']);
  $paramArray = null;
  $paramArray['user_id'] = mysql_real_escape_string($id);
  $paramArray['gal_rights'] = $usersGalleryRights;
  return \controller\SQLManipulator::execute('select-user-gallery', $paramArray);
}

function getSectionsByUserId()
{
  $paramArray = null;
  $paramArray['user_id'] = $_SESSION['id'];
  return \controller\SQLManipulator::execute('select-section-by-user-id', $paramArray);
}


function getTopic($id)
{
  $paramArray = null;
  $paramArray['user_id'] = $_SESSION['id'];
  $paramArray['topic_id'] = mysql_real_escape_string($id);
  return \controller\SQLManipulator::execute('select-topic', $paramArray);
}

function getTopicComments($start, $end, $topicId)
{
  $paramArray = null;
  $paramArray['start'] = $start - 1;
  $paramArray['end'] = $end;
  $paramArray['topic_id'] = $topicId;
  return \controller\SQLManipulator::execute('select-topic-comments', $paramArray);
}

function getTopicComment($commentId)
{
  $paramArray = null;
  $paramArray['comment_id'] = $commentId;
  return \controller\SQLManipulator::execute('select-topic-comment', $paramArray);
}

function getTopicCommentImages($commentId)
{
  $paramArray = null;
  $paramArray['comment_id'] = $commentId;
  return \controller\SQLManipulator::execute('select-topic-comment-images', $paramArray);
}

function isSubscribedToTopic($topicId)
{
  $paramArray = null;
  $paramArray['topic_id'] = $topicId;
  $paramArray['user_id'] = $_SESSION['id'];
  $resultSet = \controller\SQLManipulator::execute('select-is-subscribed-to-topic', $paramArray);
  if ($resultSet) {
    if (mysql_fetch_assoc($resultSet)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }

}

function getDialogs()
{
  $paramArray = null;
  $paramArray['sender_id'] = $_SESSION['id'];
  $paramArray['getter_id'] = $_SESSION['id'];
  $paramArray['sender_check_id'] = $_SESSION['id'];
  return \controller\SQLManipulator::execute('select-user-dialogs', $paramArray);
}

function getDialogLastMsgInfo($dialogId)
{
  $paramArray = null;
  $paramArray['dialog_id'] = mysql_real_escape_string($dialogId);
  return \controller\SQLManipulator::execute('select-dialog-last-msg-info', $paramArray);
}

function countDialogMessages($dialogId)
{
  $paramArray = null;
  $paramArray['dialog_id'] = mysql_real_escape_string($dialogId);
  $resultSet = \controller\SQLManipulator::execute('select-count-dialog-messages', $paramArray);
  if ($resultSet) {
    $resultRow = mysql_fetch_assoc($resultSet);
    return $resultRow['msg'];
  } else {
    return 0;
  }
}

function isConversationMember()
{
  $paramArray = null;
  $paramArray['sender_id'] = $_SESSION['id'];
  $paramArray['getter_id'] = $_SESSION['id'];

  $resultSet = \controller\SQLManipulator::execute('select-is-conv-member', $paramArray);
  if ($resultSet) {
    if (mysql_fetch_assoc($resultSet)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

function getConversation($dialogId)
{
  $paramArray = null;
  $paramArray['dialog_id'] = mysql_real_escape_string($dialogId);
  return \controller\SQLManipulator::execute('select-conv', $paramArray);
}

function getDialogPartner($dialogId)
{
  $paramArray = null;
  $paramArray['sender_id'] = $_SESSION['id'];
  $paramArray['dialog_id'] = mysql_real_escape_string($dialogId);
  $resultSet = \controller\SQLManipulator::execute('select-dialog-partner', $paramArray);

  if ($resultSet) {
    if ($partnerRow = mysql_fetch_assoc($resultSet)) {
      echo $partnerRow['partner'];
    }
  }
}

function checkIfDialogRead($dialogId)
{
  $paramArray = null;
  $paramArray['user_id'] = $_SESSION['id'];
  $paramArray['dialog_id'] = mysql_real_escape_string($dialogId);
  \controller\SQLManipulator::execute('update-dialog-read', $paramArray);
}

function getLastGalleryImages()
{
  return \controller\SQLManipulator::execute('select-last-gallery-images', null);
}

function getAllGalleryImages()
{
  return \controller\SQLManipulator::execute('select-all-gallery-images', null);
}

function getGalleryImg($imageId)
{
  $paramArray = null;
  $paramArray['gallery_id'] = $imageId;
  return \controller\SQLManipulator::execute('select-gallery-image', $paramArray);
}

function getGalleryImgComments($start, $end, $imageId)
{
  $paramArray = null;
  $paramArray['image_id'] = $imageId;
  $paramArray['start'] = $start - 1;
  $paramArray['end'] = $end;
  return \controller\SQLManipulator::execute('select-gallery-image-comments', $paramArray);
}

function countGalleryImageComments($imageId)
{
  $paramArray = null;
  $paramArray['gallery_id'] = $imageId;
  $topicSet = \controller\SQLManipulator::execute('select-count-gallery-image-comments', $paramArray);
  $topic = mysql_fetch_assoc($topicSet);

  if ($topicSet) {
    return $topic['cmsg'];
  } else {
    return 0;
  }
}

function getGalleryComment($commentId)
{
  $paramArray = null;
  $paramArray['comment_id'] = $commentId;
  return \controller\SQLManipulator::execute('select-gallery-image-comment-by-id', $paramArray);
}

function getLastFlies()
{
  return \controller\SQLManipulator::execute('select-last-flies', null);
}

function getAllFlies()
{
  return \controller\SQLManipulator::execute('select-all-flies', null);
}

function countFlyComments($flyId)
{
  $paramArray = null;
  $paramArray['fly_id'] = $flyId;
  $resultSet = \controller\SQLManipulator::execute('count-fly-comments', $paramArray);

  if ($resultSet) {
    if ($row = mysql_fetch_assoc($resultSet)) {
      return $row['comments'];
    } else {
      return 0;
    }
  } else {
    return 0;
  }
}

function getFlyById($flyid)
{
  $paramArray = null;
  $paramArray['fly_id'] = $flyid;
  return \controller\SQLManipulator::execute('select-fly-by-id', $paramArray);
}

function getFlyImages($flyId, $mainImgId)
{
  $paramArray = null;
  $paramArray['fly_id'] = $flyId;
  $paramArray['main_img_id'] = $mainImgId;
  return \controller\SQLManipulator::execute('select-fly-images', $paramArray);
}

function getFlyComments($start, $end, $flyId)
{
  $paramArray = null;
  $paramArray['start'] = mysql_real_escape_string($start);
  $paramArray['end'] = mysql_real_escape_string($end);
  $paramArray['fly_id'] = mysql_real_escape_string($flyId);
  return \controller\SQLManipulator::execute('select-fly-comments', $paramArray);
}

function getFlyComment($commentId)
{
  $parseArray = null;
  $parseArray['comment_id'] = $commentId;
  return \controller\SQLManipulator::execute('select-fly-comment-by-id', $parseArray);
}

function encryptString($login, $password)
{
  $tmpLogin = hash("tiger192,3", $login);
  $tmpConnector = hash("gost", "theFlyNet");
  $tmpPassword = hash("haval224,3", $password);
  $encryptedString = hash("snefru256", $tmpLogin . $tmpConnector . $tmpPassword);
  return $encryptedString;
}

function loginUser($login, $password)
{
  $paramArray = null;
  $paramArray['login'] = $login;
  $paramArray['pass'] = encryptString($login, $password);

  $resultSet = \controller\SQLManipulator::execute('select-login-user', $paramArray);

  if ($row = mysql_fetch_assoc($resultSet)) {
    session_start();
    $_SESSION['id'] = $row['id'];
    $timeStamp = getLocalTimeStamp();
    $paramArray = null;
    $paramArray['user_id'] = $row['id'];
    $paramArray['date'] = mysql_real_escape_string(f_Date($timeStamp));
    $paramArray['time'] = mysql_real_escape_string(f_Time($timeStamp));
    \controller\SQLManipulator::execute('insert-new-visit', $paramArray);
    setLanguage();
    return true;
  } else {
    return false;
  }

}

function getLastNews()
{
  return \controller\SQLManipulator::execute('select-last-news', null);
}

function getRandomSizeText($start, $end, $fullText)
{
  mt_srand();
  $length = mt_rand($start, $end);

  if (strlen($fullText) < $length) {
    $length = strlen($fullText);
  } else if ($fullText{$length} != " ") {
    $length = strpos($fullText, " ", $length);
  }

  return substr($fullText, 0, $length) . "..";
}

function getAllNews()
{
  return \controller\SQLManipulator::execute('select-all-articles', null);
}

function getNewsImages($newsId)
{
  $paramArray = null;
  $paramArray['news_id'] = $newsId;
  return \controller\SQLManipulator::execute('select-articles-images', $paramArray);
}

function checkTopicRead($topicId)
{
  $paramArray = null;
  $paramArray['topic_id'] = $topicId;
  $paramArray['user_id'] = $_SESSION['id'];
  return \controller\SQLManipulator::execute('update-topic-read', $paramArray);
}

function checkDialogCreated($userId)
{
  $paramArray = null;
  $paramArray['sender_user_id'] = $_SESSION['id'];
  $paramArray['getter_user_id'] = $_SESSION['id'];
  $paramArray['getter_other_id'] = $userId;
  $paramArray['sender_other_id'] = $userId;
  $resultSet = \controller\SQLManipulator::execute('select-dialog-exists', $paramArray);

  if ($resultSet) {
    if ($row = mysql_fetch_assoc($resultSet)) {
      return $row['id'];
    } else {
      return 0;
    }
  } else {
    return 0;
  }


}

function createDialog($userId)
{
  $paramArray = null;
  $paramArray['user_id'] = $_SESSION['id'];
  $paramArray['other_user_id'] = $userId;
  \controller\SQLManipulator::execute('insert-new-dialog', $paramArray);
  return mysql_insert_id();
}

function searchUsers($userName)
{
  $paramArray = null;
  $paramArray['user_name'] = $userName;
  $paramArray['user_id'] = $_SESSION['id'];
  return \controller\SQLManipulator::execute('select-search-users', $paramArray);
}

function increaseUsersMessages()
{
  $paramArray = null;
  $paramArray['user_id'] = $_SESSION['id'];
  \controller\SQLManipulator::execute('update-increase-user-messages', $paramArray);
}

function checkUserMail($mail)
{
  $paramArray = null;
  $paramArray['email'] = trim(mysql_real_escape_string($mail));
  $resultSet = \controller\SQLManipulator::execute('select-check-user-mail', $paramArray);
  if ($resultSet) {
    if ($row = mysql_fetch_assoc($resultSet)) {
      return $row;
    } else {
      return null;
    }
  } else {
    return null;
  }
}

function isLiked($content, $contentId)
{
  $paramArray = null;
  $paramArray['content_id'] = mysql_real_escape_string($contentId);

  switch ($content) {
    case "r":
      $paramArray['ind'] = 'r';
      break;
    case "t":
      $paramArray['ind'] = 't';
      break;
    case "i":
      $paramArray['ind'] = 'i';
      break;
    case "g":
      $paramArray['ind'] = 'g';
      break;
    case "f":
      $paramArray['ind'] = 'f';
      break;
    case "c":
      $paramArray['ind'] = 'c';
      break;
  }
  $resultSet = \controller\SQLManipulator::execute('select-likes-by-indicator', $paramArray);
  if ($resultSet) {
    if ($row = mysql_fetch_assoc($resultSet)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

function isDisliked($content, $contentId)
{
  $paramArray = null;
  $paramArray['content_id'] = mysql_real_escape_string($contentId);

  switch ($content) {
    case "r":
      $paramArray['ind'] = 'r';
      break;
    case "t":
      $paramArray['ind'] = 't';
      break;
    case "i":
      $paramArray['ind'] = 'i';
      break;
    case "g":
      $paramArray['ind'] = 'g';
      break;
    case "f":
      $paramArray['ind'] = 'f';
      break;
    case "c":
      $paramArray['ind'] = 'c';
      break;
  }

  $resultSet = \controller\SQLManipulator::execute('select-dislikes-by-indicator', $paramArray);

  if ($resultSet) {
    if ($row = mysql_fetch_assoc($resultSet)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

function isSpammed($content, $contentId)
{

  $paramArray = null;
  $paramArray['content_id'] = $contentId;
  $paramArray['user_id'] = $_SESSION['id'];
  $resultSet = null;

  switch ($content) {
    case "r":
      $paramArray['table'] = 'respspam';
      $paramArray['field'] = 'respid';
      break;
    case "t":
      $paramArray['table'] = 'topicspam';
      $paramArray['field'] = 'topicmsgid';
      break;
    case "g":
      $paramArray['table'] = 'galspam';
      $paramArray['field'] = 'galid';
      break;
    case "c":
      $paramArray['table'] = 'flyspam';
      $paramArray['field'] = 'flycommentid';
      break;
  }
  $resultSet = \controller\SQLManipulator::execute('select-is-spammed-by-indicator', $paramArray);

  if ($resultSet) {
    if ($row = mysql_fetch_assoc($resultSet)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

function getSections()
{
  return \controller\SQLManipulator::execute('select-sections', null);
}

function canSeeTopic($topicId)
{
  $paramArray = null;
  $paramArray['user_id'] = $_SESSION['id'];
  $paramArray['topic_id'] = $topicId;
  $resultSet = \controller\SQLManipulator::execute('select-can-see-topic', $paramArray);
  if ($resultSet) {
    if ($row = mysql_fetch_assoc($resultSet)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

function isWaitingForGroup($groupId)
{
  $paramArray = null;
  $paramArray['user_id'] = $_SESSION['id'];
  $paramArray['group_id'] = mysql_real_escape_string($groupId);
  $resultSet = \controller\SQLManipulator::execute('select-user-is-waiting-for-group', $paramArray);
  if ($resultSet) {
    if ($row = mysql_fetch_assoc($resultSet)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

function redirect($url)
{
  echo "<script language='JavaScript'>
        location.href = '" . $url . "'
    </script>";
//    header("Location: " . $url);
}

function generatePassword($length)
{
  $chars = 'abdefhiknrstyzABDEFGHKNQRSTYZ23456789';
  $numChars = strlen($chars);
  $string = '';
  for ($i = 0; $i < $length; $i++) {
    $string .= substr($chars, rand(1, $numChars) - 1, 1);
  }
  return $string;
}

function getTextWithAcronym($text, $length)
{
  return "<acronym title='" . $text . "'>" . substr($text, 0, $length) . "</acronym>";
}

function getLocalTimeStamp()
{
  date_default_timezone_get("Europe/Minsk");
  return getdate()[0];
}

function f_Date($timeStamp)
{
  date_default_timezone_set('Europe/Minsk');
  return date("Y-m-d", $timeStamp);
}

function f_Time($timeStamp)
{
  date_default_timezone_set('Europe/Minsk');
  return date("H:i:s", $timeStamp);
}

function hasNewMessages()
{
  $paramArray = null;
  $paramArray['group_id'] = $_SESSION['id'];

  $resultSet = \controller\SQLManipulator::execute('select-has-new-messages', $paramArray);

  if ($resultSet) {
    if ($row = mysql_fetch_assoc($resultSet)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

function processText($text)
{
  $text = strip_tags($text);

  $preg_autolinks = array(
    'pattern' => array(
      "'[\w\+]+://[A-z0-9\.\?\+\-/_=&%#:;]+[\w/=]+'si",
      "'([^/])(www\.[A-z0-9\.\?\+\-/_=&%#:;]+[\w/=]+)'si",
    ),
    'replacement' => array(
      '<a href="$0" target="_blank" style="color: rgba(0,0,0,0.8); font-weight: bold;" rel="nofollow">$0</a>',
      '$1<a href="http://$2" target="_blank" rel="nofollow">$2</a>',
    ));
  $search = $preg_autolinks['pattern'];
  $replace = $preg_autolinks['replacement'];
  $text = preg_replace($search, $replace, $text);
  $text = str_replace("\t", "    ", $text);
  return nl2br($text);
}

function hasNewTopicMessages()
{
  $paramArray = null;
  $paramArray['user_id'] = $_SESSION['id'];
  $resultSet = \controller\SQLManipulator::execute('select-has-new-topic-msgs', $paramArray);

  if ($resultSet) {
    if ($row = mysql_fetch_assoc($resultSet)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

function checkCommentAuthor($topicId, $commentId)
{
  $paramArray = null;
  $paramArray['user_id'] = $_SESSION['id'];
  $paramArray['topic_id'] = $topicId;
  $paramArray['msg_id'] = $commentId;
  $resultSet = \controller\SQLManipulator::execute('select-check-comment-author', $paramArray);

  if ($resultSet) {
    if ($row = mysql_fetch_assoc($resultSet)) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

function getArticle($nid)
{
  $paramArray = null;
  $paramArray['new_id'] = $nid;
  return \controller\SQLManipulator::execute('select-article', $paramArray);
}